<template>
  <div class="error-question-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">错题本</h1>
      <div class="header-actions">
        <el-button @click="exportErrorQuestions">
          <el-icon><Download /></el-icon>
          导出错题
        </el-button>
        <el-button @click="clearAllErrorQuestions">
          <el-icon><Delete /></el-icon>
          清空错题本
        </el-button>
      </div>
    </div>

    <!-- 错题统计卡片 -->
    <div class="error-stats">
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-number">{{ totalErrorQuestions }}</div>
          <div class="stat-label">总错题数</div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-number">{{ reviewedErrorQuestions }}</div>
          <div class="stat-label">已复习</div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-number">{{ masteryRate }}%</div>
          <div class="stat-label">掌握率</div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-number">{{ latestErrorDate }}</div>
          <div class="stat-label">最近错题</div>
        </div>
      </el-card>
    </div>

    <!-- 错题内容 -->
    <el-card class="error-questions-card">
      <!-- 筛选和搜索 -->
      <div class="error-questions-header">
        <div class="search-filter">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索错题..."
            prefix-icon="Search"
            class="search-input"
            @keyup.enter="searchErrorQuestions"
          />
          
          <el-select v-model="errorType" placeholder="选择题型" class="filter-select">
            <el-option label="全部" value="all" />
            <el-option label="图形推理" value="graphic" />
            <el-option label="定义判断" value="definition" />
            <el-option label="类比推理" value="analogy" />
            <el-option label="逻辑判断" value="logic" />
            <el-option label="言语理解" value="language" />
            <el-option label="数量关系" value="quantity" />
            <el-option label="资料分析" value="data" />
          </el-select>
          
          <el-select v-model="errorSource" placeholder="选择来源" class="filter-select">
            <el-option label="全部" value="all" />
            <el-option label="国考真题" value="national" />
            <el-option label="省考真题" value="provincial" />
            <el-option label="模拟题" value="simulation" />
            <el-option label="专项练习" value="special" />
          </el-select>
        </div>
        
        <div class="error-questions-actions">
          <el-button type="primary" @click="batchMarkAsReviewed" :disabled="selectedErrorQuestions.length === 0">
            <el-icon><Check /></el-icon>
            标记为已复习
          </el-button>
          <el-button @click="batchDeleteErrorQuestions" :disabled="selectedErrorQuestions.length === 0">
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </div>
      </div>

      <!-- 错题列表 -->
      <div class="error-questions-list">
        <el-table
          v-loading="loading"
          :data="errorQuestions"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          
          <el-table-column prop="id" label="题号" width="80" />
          
          <el-table-column prop="questionContent" label="题目" width="500">
            <template #default="scope">
              <div class="question-content" @click="viewErrorQuestionDetails(scope.row.id)">
                {{ scope.row.questionContent }}
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="questionType" label="题型" width="120">
            <template #default="scope">
              <el-tag>{{ getTypeName(scope.row.questionType) }}</el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="questionDifficulty" label="难度" width="100">
            <template #default="scope">
              <el-tag type="info">{{ getDifficultyName(scope.row.questionDifficulty) }}</el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="errorTime" label="错误日期" width="120">
            <template #default="scope">
              {{ new Date(scope.row.errorTime).toLocaleDateString() }}
            </template>
          </el-table-column>
          
          <el-table-column prop="isReviewed" label="是否复习" width="100">
            <template #default="scope">
              <el-switch
                v-model="scope.row.isReviewed"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="updateReviewedStatus(scope.row.id)"
              />
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="scope">
              <el-button type="text" @click="viewErrorQuestionDetails(scope.row.id)">
                查看详情
              </el-button>
              <el-button type="text" danger @click="deleteErrorQuestion(scope.row.id)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="error-questions-pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 错题详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="错题详情"
      width="800px"
      :fullscreen="isFullscreen"
    >
      <div v-if="currentErrorQuestion" class="error-question-detail">
        <div class="question-header">
          <div class="question-id">{{ currentErrorQuestion.id }}</div>
          <div class="question-meta">
            <el-tag>{{ getTypeName(currentErrorQuestion.questionType) }}</el-tag>
            <el-tag type="info">{{ getDifficultyName(currentErrorQuestion.questionDifficulty) }}</el-tag>
            <span class="error-date">错误日期：{{ new Date(currentErrorQuestion.errorTime).toLocaleDateString() }}</span>
          </div>
        </div>
        
        <div class="question-content-detail">
          <h3>题目内容：</h3>
          <p>{{ currentErrorQuestion.questionContent }}</p>
        </div>
        
        <div class="answer-comparison">
          <h3>答案对比：</h3>
          <div class="answer-item">
            <span class="answer-label">你的答案：</span>
            <span class="your-answer">{{ currentErrorQuestion.userAnswer }}</span>
          </div>
          <div class="answer-item">
            <span class="answer-label">正确答案：</span>
            <span class="correct-answer">{{ currentErrorQuestion.correctAnswer }}</span>
          </div>
        </div>
        
        <div class="error-reason">
          <h3>错误原因：</h3>
          <el-input
            v-model="currentErrorQuestion.errorReason"
            type="textarea"
            placeholder="请输入错误原因..."
            @change="handleUpdateErrorReason"
          />
        </div>
        
        <div class="correct-solution">
          <h3>错误原因：</h3>
          <p>{{ currentErrorQuestion.errorReason || '暂无错误原因' }}</p>
        </div>
        
        <div class="review-notes">
          <h3>复习笔记：</h3>
          <el-input
            v-model="currentErrorQuestion.reviewNotes"
            type="textarea"
            placeholder="请输入复习笔记..."
            @change="handleUpdateReviewNotes"
          />
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="toggleFullscreen">
            <el-icon>{{ isFullscreen ? 'MinusSquare' : 'PlusSquare' }}</el-icon>
            {{ isFullscreen ? '退出全屏' : '全屏查看' }}
          </el-button>
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="danger" @click="deleteErrorQuestion">删除错题</el-button>
          <el-button type="primary" @click="handleUpdateErrorReason">保存修改</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getWrongQuestions, 
  searchWrongQuestions, 
  getWrongQuestionsByType, 
  updateReviewStatus,
  deleteWrongQuestion,
  deleteWrongQuestions,
  clearWrongQuestions,
  getWrongQuestionStats,
  type WrongQuestion,
  type WrongQuestionStats
} from '@/api/wrong-question'

// 响应式数据
const searchKeyword = ref('')
const errorType = ref('all')
const errorSource = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const selectedErrorQuestions = ref<WrongQuestion[]>([])
const detailDialogVisible = ref(false)
const isFullscreen = ref(false)
const currentErrorQuestion = ref<WrongQuestion | null>(null)

// 错题数据
const errorQuestions = ref<WrongQuestion[]>([])
const totalCount = ref(0)
const stats = ref<WrongQuestionStats>({
  totalCount: 0,
  reviewedCount: 0,
  unreviewedCount: 0,
  masteryRate: 0,
  latestErrorDate: '暂无'
})

// 用户ID（暂时使用固定值，实际应该从用户状态获取）
const userId = ref(1)

// 计算属性：统计数据
const totalErrorQuestions = computed(() => stats.value.totalCount)
const reviewedErrorQuestions = computed(() => stats.value.reviewedCount)
const masteryRate = computed(() => stats.value.masteryRate)
const latestErrorDate = computed(() => stats.value.latestErrorDate)

// 获取题型名称
const getTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    SINGLE_CHOICE: '单选题',
    MULTIPLE_CHOICE: '多选题',
    TRUE_FALSE: '判断题',
    FILL_BLANK: '填空题',
    ESSAY: '论述题',
    SHORT_ANSWER: '简答题'
  }
  return typeMap[type] || type
}

// 获取难度名称
const getDifficultyName = (difficulty: string) => {
  const difficultyMap: Record<string, string> = {
    EASY: '简单',
    MEDIUM: '中等',
    HARD: '困难'
  }
  return difficultyMap[difficulty] || difficulty
}

// 加载错题列表
const loadErrorQuestions = async () => {
  try {
    loading.value = true
    const response = await getWrongQuestions({
      userId: userId.value,
      page: currentPage.value - 1,
      size: pageSize.value,
      sortBy: 'errorTime',
      sortOrder: 'desc'
    })
    
    if (response.success) {
      errorQuestions.value = response.data.content || []
      totalCount.value = response.data.totalElements || 0
    } else {
      ElMessage.error('加载错题列表失败: ' + response.message)
    }
  } catch (error) {
    console.error('加载错题列表失败:', error)
    ElMessage.error('加载错题列表失败')
  } finally {
    loading.value = false
  }
}

// 加载统计信息
const loadStats = async () => {
  try {
    const response = await getWrongQuestionStats(userId.value)
    if (response.success) {
      stats.value = response.data
    }
  } catch (error) {
    console.error('加载统计信息失败:', error)
  }
}

// 搜索错题
const searchErrorQuestions = async () => {
  try {
    loading.value = true
    currentPage.value = 1
    
    let response
    if (searchKeyword.value.trim()) {
      response = await searchWrongQuestions({
        userId: userId.value,
        keyword: searchKeyword.value.trim(),
        page: currentPage.value - 1,
        size: pageSize.value
      })
    } else if (errorType.value !== 'all') {
      response = await getWrongQuestionsByType({
        userId: userId.value,
        type: errorType.value,
        page: currentPage.value - 1,
        size: pageSize.value
      })
    } else {
      response = await getWrongQuestions({
        userId: userId.value,
        page: currentPage.value - 1,
        size: pageSize.value,
        sortBy: 'errorTime',
        sortOrder: 'desc'
      })
    }
    
    if (response.success) {
      errorQuestions.value = response.data.content || []
      totalCount.value = response.data.totalElements || 0
    } else {
      ElMessage.error('搜索错题失败: ' + response.message)
    }
  } catch (error) {
    console.error('搜索错题失败:', error)
    ElMessage.error('搜索错题失败')
  } finally {
    loading.value = false
  }
}

// 处理选择变化
const handleSelectionChange = (val: any[]) => {
  selectedErrorQuestions.value = val
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadErrorQuestions()
}

// 处理当前页码变化
const handleCurrentChange = (current: number) => {
  currentPage.value = current
  loadErrorQuestions()
}

// 查看错题详情
const viewErrorQuestionDetails = (id: number) => {
  const question = errorQuestions.value.find(q => q.id === id)
  if (question) {
    currentErrorQuestion.value = { ...question }
    detailDialogVisible.value = true
  }
}

// 更新复习状态
const updateReviewedStatus = async (id: number) => {
  try {
    const question = errorQuestions.value.find(q => q.id === id)
    if (question) {
      const masteryLevel = question.isReviewed ? (question.masteryLevel || 50) : undefined
      const response = await updateReviewStatus(id, !question.isReviewed, masteryLevel)
      
      if (response.success) {
        question.isReviewed = !question.isReviewed
        if (question.isReviewed && !question.masteryLevel) {
          question.masteryLevel = 50
        }
        ElMessage.success('复习状态已更新')
        loadStats() // 重新加载统计信息
      } else {
        ElMessage.error('更新复习状态失败: ' + response.message)
      }
    }
  } catch (error) {
    console.error('更新复习状态失败:', error)
    ElMessage.error('更新复习状态失败')
  }
}

// 更新错误原因
const handleUpdateErrorReason = async () => {
  if (currentErrorQuestion.value) {
    try {
      // 这里应该调用API，但API函数不存在，暂时注释掉
      // const response = await updateErrorReason(currentErrorQuestion.value.id, currentErrorQuestion.value.errorReason)
      
      // 暂时直接更新本地数据
      const question = errorQuestions.value.find(q => q.id === currentErrorQuestion.value!.id)
      if (question) {
        question.errorReason = currentErrorQuestion.value.errorReason
      }
      ElMessage.success('错误原因已更新')
    } catch (error) {
      console.error('更新错误原因失败:', error)
      ElMessage.error('更新错误原因失败')
    }
  }
}

// 更新复习笔记
const handleUpdateReviewNotes = async () => {
  if (currentErrorQuestion.value) {
    try {
      // 这里应该调用API，但API函数不存在，暂时注释掉
      // const response = await updateReviewNotes(currentErrorQuestion.value.id, currentErrorQuestion.value.reviewNotes)
      
      // 暂时直接更新本地数据
      const question = errorQuestions.value.find(q => q.id === currentErrorQuestion.value!.id)
      if (question) {
        question.reviewNotes = currentErrorQuestion.value.reviewNotes
      }
      ElMessage.success('复习笔记已更新')
    } catch (error) {
      console.error('更新复习笔记失败:', error)
      ElMessage.error('更新复习笔记失败')
    }
  }
}

// 批量标记为已复习
const batchMarkAsReviewed = async () => {
  try {
    const promises = selectedErrorQuestions.value.map(item => 
      updateReviewStatus(item.id, true, 50)
    )
    
    await Promise.all(promises)
    selectedErrorQuestions.value = []
    ElMessage.success('已批量标记为已复习')
    loadErrorQuestions() // 重新加载数据
    loadStats() // 重新加载统计信息
  } catch (error) {
    console.error('批量标记失败:', error)
    ElMessage.error('批量标记失败')
  }
}

// 删除错题
const deleteErrorQuestion = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该错题吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deleteWrongQuestion(id)
    if (response.success) {
      ElMessage.success('错题已删除')
      loadErrorQuestions() // 重新加载数据
      loadStats() // 重新加载统计信息
    } else {
      ElMessage.error('删除错题失败: ' + response.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除错题失败:', error)
      ElMessage.error('删除错题失败')
    }
  }
}

// 批量删除错题
const batchDeleteErrorQuestions = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedErrorQuestions.value.length} 条错题吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const selectedIds = selectedErrorQuestions.value.map(q => q.id)
    const response = await deleteWrongQuestions(selectedIds)
    
    if (response.success) {
      selectedErrorQuestions.value = []
      ElMessage.success(`成功删除 ${selectedIds.length} 条错题`)
      loadErrorQuestions() // 重新加载数据
      loadStats() // 重新加载统计信息
    } else {
      ElMessage.error('批量删除失败: ' + response.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 清空错题本
const clearAllErrorQuestions = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空整个错题本吗？此操作不可恢复！',
      '确认清空',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    const response = await clearWrongQuestions(userId.value)
    if (response.success) {
      selectedErrorQuestions.value = []
      currentPage.value = 1
      ElMessage.success('错题本已清空')
      loadErrorQuestions() // 重新加载数据
      loadStats() // 重新加载统计信息
    } else {
      ElMessage.error('清空错题本失败: ' + response.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空错题本失败:', error)
      ElMessage.error('清空错题本失败')
    }
  }
}

// 导出错题
const exportErrorQuestions = () => {
  // 这里只是模拟导出功能
  ElMessage.success('错题导出功能待实现')
}

// 切换全屏
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value
}

// 组件挂载时初始化
onMounted(async () => {
  await loadStats()
  await loadErrorQuestions()
})
</script>

<style lang="scss" scoped>
.error-question-view {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.error-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 12px;
  overflow: hidden;
}

.stat-item {
  text-align: center;
  padding: 20px;
}

.stat-number {
  font-size: 32px;
  font-weight: 700;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
}

.error-questions-card {
  border-radius: 12px;
  overflow: hidden;
}

.error-questions-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e5e7eb;
  flex-wrap: wrap;
  gap: 15px;
}

.search-filter {
  display: flex;
  gap: 15px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  width: 300px;
}

.filter-select {
  width: 150px;
}

.error-questions-actions {
  display: flex;
  gap: 10px;
}

.error-questions-list {
  padding: 20px;
}

.question-content {
  color: #409eff;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  &:hover {
    text-decoration: underline;
  }
}

.error-questions-pagination {
  padding: 20px;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #e5e7eb;
}

.error-question-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e5e7eb;
}

.question-id {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.question-meta {
  display: flex;
  align-items: center;
  gap: 10px;
}

.error-date {
  font-size: 14px;
  color: #6b7280;
}

.question-content-detail,
.question-options,
.error-reason,
.correct-solution,
.review-notes {
  margin-bottom: 20px;
}

.question-content-detail h3,
.question-options h3,
.error-reason h3,
.correct-solution h3,
.review-notes h3 {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 10px;
}

.question-content-detail p {
  font-size: 14px;
  line-height: 1.8;
  color: #4b5563;
  white-space: pre-wrap;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  font-size: 14px;
  color: #4b5563;
}

.option-label {
  width: 30px;
  font-weight: 600;
}

.option-content {
  flex: 1;
}

.your-answer {
  margin-left: 10px;
  color: #f56c6c;
  font-size: 12px;
}

.correct-answer {
  margin-left: 10px;
  color: #67c23a;
  font-size: 12px;
}

.correct-solution pre {
  background-color: #f9fafb;
  padding: 15px;
  border-radius: 6px;
  font-size: 14px;
  line-height: 1.8;
  color: #4b5563;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>